package com.lottotest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ResultActivity extends Activity {

	EditText input_num;
	TextView luck_num;
	Button result_btn;
	Button map_btn;
	String num_chk;
	static final int DIALOG_1 = 0;
	private NotificationManager nm = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_result);

		input_num = (EditText) findViewById(R.id.inputnum);
		luck_num = (TextView) findViewById(R.id.lucknum);
		result_btn = (Button) findViewById(R.id.resultButton);
		map_btn = (Button) findViewById(R.id.mapButton);

		map_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(ResultActivity.this,
						GpsActivity.class);
				startActivity(intent);
			}
		});

		result_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				num_chk = input_num.getText().toString().trim();
				if (num_chk.equals("")) {
					AlertDialog alert = new AlertDialog.Builder(
							ResultActivity.this)
							.setTitle("안내")
							.setMessage("회차를 입력해주세요.")
							.setPositiveButton("확인",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub
											dialog.dismiss();

										}
									}).show();
				} else {
					new getLuckNum().execute();
				}
			}
		});
	}

	class getLuckNum extends AsyncTask<String, String, String> {

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(String result) {

			super.onPostExecute(result);

			luck_num.setText(result);

			nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			// PendingIntent를 등록 하고, noti를 클릭시에 어떤 클래스를 호출 할 것인지 등록.
			PendingIntent intent = PendingIntent.getActivity(
					ResultActivity.this, 0, new Intent(ResultActivity.this,
							NotificationConfirm.class), 0);

			// status bar 에 등록될 메시지(Tiker, 아이콘, 그리고 noti가 실행될 시간)
			Notification notification = new Notification(
					android.R.drawable.ic_dialog_alert, num_chk + "차 조회번호", System.currentTimeMillis());

			// List에 표시될 항목
			notification.setLatestEventInfo(ResultActivity.this, num_chk + "차 1등 번호", result, intent);

			// noti를 클릭 했을 경우 자동으로 noti Icon 제거
			 notification.flags = notification.flags | notification.FLAG_AUTO_CANCEL;

			// 1234 notification 의 고유아이디
			nm.notify(1234, notification);
		}

		@Override
		protected void onPreExecute() {

		}

		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);

		}

		@Override
		protected String doInBackground(String... params) {

			InputStream is = null;
			String result = null;
			String nums = null;

			String c_id = input_num.getText().toString();

			String getUrl = "http://lotto.kaisyu.com/api?method=get&gno=" + c_id + "";

			try {
				DefaultHttpClient httpclient = new DefaultHttpClient();
				HttpGet httpget = new HttpGet(getUrl);
				HttpParams paramss = httpclient.getParams();
				HttpConnectionParams.setConnectionTimeout(paramss, 5000);
				HttpConnectionParams.setSoTimeout(paramss, 5000);
				HttpResponse response = httpclient.execute(httpget);
				HttpEntity entityResponse = response.getEntity();
				is = entityResponse.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "utf-8"), 8);

				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line).append("\n");
				}
				is.close();
				result = sb.toString();

				try {

					JSONObject jsonObject = new JSONObject(result);

					nums = jsonObject.getString("nums").toString();

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
			return nums;
		}
	}

	public class NotificationConfirm extends Activity {

		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);

			// notification 매니저 생성
			NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

			// 등록된 notification 을 제거 한다.
			nm.cancel(1234);

		}
	}

}
